#include "MinMax.h"

MinMax::MinMax(void)
{
}

MinMax::~MinMax(void)
{
}


coord_t&	MinMax::launch(GameInfo& info)
{
	int		count;
	int		count2;
	int		ret = - 9000009;
	int		tmp;

	int limitXRight = ((info.getPosXRight() + 1) < LENGTHBOARD ? info.getPosXRight() + 1 : info.getPosXRight());
	int limitYBot = ((info.getPosYBot() + 1) < LENGTHBOARD ? info.getPosYBot() + 1 : info.getPosYBot());

	for (count = (info.getPosYTop() > 0 ? info.getPosYTop() - 1 : 0); count <= limitYBot; count++)
		for (count2 = (info.getPosXLeft() > 0 ? info.getPosXLeft() - 1 : 0);
			count2 <= limitXRight; count2++)
		{
			if (info.getMap()[count][count2] == 0)
			{
				fCoord.x = count2;
				fCoord.y = count;
				try
				{
					judge.putPieceOnMap2(info, fCoord);
					tmp = min(fCoord, info);
					if (tmp > ret )
					{
						ret = tmp;
						coordMax.x = fCoord.x;
						coordMax.y = fCoord.y;
					}
				}
				catch (const GameExceptionTwinTriple& e)
				{
				}
				catch(GameExceptionWinByAlignement& exc )
				{
					coordMax.x = fCoord.x;
					coordMax.y = fCoord.y;
					return coordMax;
				}
				catch ( GameExceptionWinByScore& exc)
				{
					coordMax.x = fCoord.x;
					coordMax.y = fCoord.y;
					return coordMax;
				}
			} 
		}
	return coordMax;
}

int	MinMax::min(coord_t& coord, GameInfo info)
{
	int count;
	int count2;
	int ret;
	int tmp = 9000009;
	bool init = false;
	coord_t c;

	info.putPieceOnMap(coord);
	info.endRoundOfPlayer();
	int limitXRight = ((info.getPosXRight() + 1) < LENGTHBOARD ? info.getPosXRight() + 1 : info.getPosXRight());
	int limitYBot = ((info.getPosYBot() + 1) < LENGTHBOARD ? info.getPosYBot() + 1 : info.getPosYBot());

	for (count = (info.getPosYTop() > 0 ? info.getPosYTop() - 1 : 0);
		count <= limitYBot; count++)
	{
		for (count2 = (info.getPosXLeft() > 0 ? info.getPosXLeft() - 1 : 0);
			count2 <= limitXRight; count2++)
		{
			if (info.getMap()[count][count2] == 0)
			{
				try
				{
					c.x = count2;
					c.y = count;
					judge.putPieceOnMap2(info, c);
					tmp = launchHeuristic(c, info);
					if (tmp < ret)
						ret = tmp;
				}
				catch(const GameExceptionTwinTriple& e)
				{
				}
				catch(GameExceptionWinByAlignement& exc )
				{
					return -9000000;
				}
				catch ( GameExceptionWinByScore& exc)
				{
					return -9000000;
				}
			} 
		}
	}
	return ret;
}


int	MinMax::launchHeuristic(coord_t& coord, GameInfo info)
{
	Hcalc calc(info);
	info.putPieceOnMap(coord);
	return calc.HeuCalc(coord, info);
}

